﻿using System;
using ValidationEngine.Commons;
using ValidationEngine.Commons.Enums;
using ValidationEngine.Commons.Interfaces;
using ValidationEngine.Tools;

namespace ValidationEngine.ValidationRules
{
   public class RangeRule: BaseValidationRule
   {
       #region Members
       private readonly decimal _minValue;
       private readonly decimal _maxValue;
       private readonly bool _inRange = true; 
       #endregion

       #region Ctor
       public RangeRule(
        decimal min,
        decimal max,
        bool shouldBeInRange,
        string defErrorText = null,
        RuleApplingContext applyCtx = RuleApplingContext.Always,
        ValidationErrorType errorType = ValidationErrorType.Error)
       {
           this._maxValue = max;
           this._minValue = min;
           this._inRange = shouldBeInRange;
           this.ApplingContext = applyCtx;
           this._defErrorType = errorType;
           this._defErrorMsg = defErrorText ?? String.Format("Value should {0} be in range ({1} : {2})", shouldBeInRange ? "" : "not", _minValue, _maxValue);
       } 
       #endregion

      protected override IValidationInfo ApplyRule(IValidationContext ctx)
      {
         var modelValue = ModelHelper.GetDecimal(ctx);
         if (!modelValue.HasValue)
         {
            return Result;
         }
         if (_inRange)
         {
             DefResult = modelValue.Value >= _minValue && modelValue.Value <= _maxValue ? null : _defErrorMsg;
         }
         else
         {
             DefResult = modelValue.Value < _minValue || modelValue.Value > _maxValue ? null : _defErrorMsg;
         }
         return Result;
      }
   }
}
